package com.dc.diffutil

import android.util.SparseArray
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView

class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

    protected val mViews : SparseArray<View> = SparseArray()

    open fun <T : View> getView(viewId: Int): T {
        var view = mViews[viewId]
        if (view == null) {
            view = itemView.findViewById(viewId)
            mViews.put(viewId, view)
        }
        return view as T
    }

    open fun setViewVisibility(viewId: Int, visibility: Int) : ViewHolder {
        getView<View>(viewId).visibility = visibility
        return this
    }

    open fun setViewVisibility(viewId: Int, visibility: Boolean) : ViewHolder {
        getView<View>(viewId).visibility = if (visibility) View.VISIBLE else View.GONE
        return this
    }

    open fun setText(viewId: Int, text: CharSequence) : ViewHolder {
        val tv = getView<TextView>(viewId)
        tv.text = text
        return this
    }

    open fun setImageResource(viewId: Int, resource: Int) : ViewHolder {
        val imageView = getView<ImageView>(viewId)
        imageView.setImageResource(resource)
        return this
    }

    open fun setImagePath(viewId: Int, path: String, imageLoader: HolderImageLoader) : ViewHolder {
        val imageView = getView<ImageView>(viewId)
        imageLoader.loadImage(imageView, path)
        return this
    }
}